﻿using PLCSharp.CoreModel.Prism;
using PLCSharp.Services;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Events;
using Prism.Ioc;
using System.Windows;

namespace PLCSharp.Views.Authority
{
    public class LoginViewModel : DialogAwareBase
    {
        public LoginModel Model { get; set; }
        public LoginViewModel(IContainerExtension container, IEventAggregator ea, IDialogService dialogService) : base(container, ea, dialogService)
        {
            Model = container.Resolve<LoginModel>();
            Title = "登录";
        }
        //public LoginViewModel(IContainerExtension container)
        //{
        //    Model = container.Resolve<LoginModel>();
        //    Title = "登录";
        //}



        private DelegateCommand<string> _closeDialogCommand;

        public new DelegateCommand<string> CloseDialogCommand =>
                _closeDialogCommand ??= new DelegateCommand<string>(ExecuteCloseDialogCommand);

        private void ExecuteCloseDialogCommand(string parameter)
        {

            switch (parameter)
            {
                case "Login":
                    if (Model.SelectUser == null) return;
                    var user = Model.UserList.Where(u => u.Password == EncryptService.Encrypt(Model.Password)
                      && u.Name == Model.SelectUser.Name).FirstOrDefault();

                    if (user == null)
                    {
                        PasswordMsg = "用户名或密码错误";
                        Model.CurrentUser = Model.UserList.Where(u => u.Name == "guest").FirstOrDefault();
                    }
                    else
                    {
                        Model.CurrentUser = user;


                    }
                    break;
                case "Logout":
                    Model.CurrentUser = Model.UserList.Where(u => u.Name == "guest").FirstOrDefault();
                    PasswordMsg = "已注销，当前用户：游客guset";

                    break;
                default:
                    break;
            }


            ButtonResult result = ButtonResult.None;

            if (parameter?.ToLower() == "manage")
            {
                if (Model.CurrentUser == null || Model.CurrentUser.Name != "admin")
                {
                    MessageBox.Show("管理用户需要admin用户", "无权限");
                    return;
                }
                result = ButtonResult.Retry;
            }
            RaiseRequestClose(new DialogResult(result));
        }



        private string _PasswordMsg;



        public string PasswordMsg
        {
            get { return _PasswordMsg; }
            set { SetProperty(ref _PasswordMsg, value); }
        }



    }
}